<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
          <Search :allOpts="formInline.allOpts" v-model="formInline.cOpts" @blur="search"></Search>
        </el-form-item>
        <el-form-item v-if="canClick">
          <el-button type="success" @click="showForm('add')" :disabled="butStatus.create">创建</el-button>
        </el-form-item>
        <el-form-item v-if="canClick">
          <el-button type="info" v-show="butStatus.upload" :disabled="butStatus.upload">上传</el-button>
          <el-upload
            v-show="!butStatus.upload"
            :action="uploadUrl"
            :headers="headers"
            :data="uploadBody"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :show-file-list=false
            :file-list="fileList"
            multiple>
            <el-button type="info">上传</el-button>
          </el-upload>
          <!--<el-button v-popover:popover :disabled="butStatus.upload">上传</el-button>-->
        </el-form-item>
        <el-form-item v-if="canClick">
          <el-button type="info" @click="readFile" :disabled="butStatus.view">查看</el-button>
        </el-form-item>
        <el-form-item v-if="canClick">
          <el-button type="info" @click="showForm('rename')" :disabled="butStatus.rename">重命名</el-button>
        </el-form-item>
        <el-form-item v-if="canClick">
          <el-button type="danger" @click="hrm" :disabled="butStatus.delete">删除</el-button>
        </el-form-item>
        <el-form-item v-if="canClick">
          <el-button type="info" @click="showForm('mv')" :disabled="butStatus.move">移动</el-button>
        </el-form-item>
        <el-form-item v-if="canClick">
          <el-button type="info" @click="showForm('merge')" :disabled="butStatus.merge">合并</el-button>
        </el-form-item>
        <el-form-item v-if="canClick">
          <el-button type="info" @click="downloadFile" :disabled="butStatus.download">下载</el-button>
        </el-form-item>
        <!--<el-form-item>
          <el-button @click="openSnapshotForm" :disabled="butStatus.snapshot">快照</el-button>
        </el-form-item>-->
      </el-form>
    </el-col>

    <!--面包屑-->
    <el-col :span="24" class="udfs-list">
      <el-breadcrumb separator="/" class="dirtips">
        <el-breadcrumb-item></el-breadcrumb-item>
        <el-breadcrumb-item v-for="(item,index) in paths">
          <nobr @click="returnRoot(index)"> {{item}}</nobr>
        </el-breadcrumb-item>
        <!--<el-breadcrumb-item>{{current_dir}}</el-breadcrumb-item>-->
      </el-breadcrumb>
    </el-col>
    <!--列表-->
    <el-col :span="24">
      <el-table :data="tableData" border style="width: 100%"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" v-if="canClick">全选</el-table-column>
        <el-table-column label="目录" sortable prop="file_name">
          <template scope="scope">
            <el-button type="text" v-if="scope.row.isdirectory=='1'" @click="updateTable(scope.row)">
              {{scope.row.file_name}}
            </el-button>
            <div type="text" v-if="scope.row.isdirectory!='1'">{{scope.row.file_name}}</div>
          </template>
        </el-table-column>
        <el-table-column label="大小(KB)" sortable>
          <template scope="scope">{{scope.row.file_sizes | fileSizeKB}}</template>
        </el-table-column>
        <el-table-column label="备份数" sortable prop="backup_num"></el-table-column>
        <el-table-column label="Block大小(MB)" sortable width="160">
          <template scope="scope">{{scope.row.block_sizes | fileSize}}</template>
        </el-table-column>
        <el-table-column label="最近修改日期" sortable width="171" prop="last_updatetime"></el-table-column>
        <el-table-column label="所有者" sortable prop="file_owner"></el-table-column>
        <el-table-column label="组" sortable prop="file_group"></el-table-column>
        <el-table-column label="权限" sortable prop="file_acl"></el-table-column>
      </el-table>
    </el-col>
    <!--分页-->
    <!--<el-col :span="24" class="toolbar" style="padding-bottom:10px;">
        <el-pagination :current-page="start_index" :page-sizes="[5, 10, 20, 50]" :page-size="page_count" layout="total, sizes, prev, pager, next, jumper" :total="count" style="float:right"></el-pagination>
    </el-col>-->

    <!--修改界面-->
    <el-dialog :title="dialog.dialogTitle" v-model="dialog.log">
      <pre style="white-space: pre-wrap;word-wrap: break-word;">
        {{fileContent}}
      </pre>
    </el-dialog>

    <!--修改界面-->
    <el-dialog v-model="dialog.form" size="tiny" :title="formTitle" @close="resetForm">
      <el-form label-position="right" :model="form" :rules="rules" ref="form" :label-width="formLabelWidth"
               size="tiny">
        <el-form-item v-if="editinpStatus.directory" label="当前目录" prop="directory" :disabled="true">
          <el-input v-model="form.hdfs_dir" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item v-if="editinpStatus.newDirectory" label="新建目录名称" prop="file_name">
          <el-input v-model="form.file_name"></el-input>
        </el-form-item>
        <el-form-item v-if="editinpStatus.upfile" label="上传文件" prop="upfile">
          <UploadPath></UploadPath>
        </el-form-item>
        <el-form-item v-if="editinpStatus.name" label="原名字" prop="name">
          <div type="text">{{form.hdfs_dir}}</div>
          <!--  <el-input v-model="form.hdfs_path"></el-input> -->
        </el-form-item>
        <el-form-item v-if="editinpStatus.newName" label="新名字" prop="newName">
          <el-input v-model="form.newName"></el-input>
        </el-form-item>

        <el-form-item v-if="editinpStatus.path" label="原路径" prop="path">
          <div type="text">{{form.hdfs_dir}}</div>
        </el-form-item>
        <el-form-item v-if="editinpStatus.newPath" label="新路径" prop="target_hdfs_path">
          <UploadPath v-model="form.target_hdfs_path"></UploadPath>
        </el-form-item>

        <el-form-item v-if="editinpStatus.selFile" label="源文件" prop="selFile">
          <!--<el-input v-model="form.hdfs_paths"></el-input>-->
          <div v-for="item in multipleSelection">{{currentDir}}/{{item.file_name}}</div>

        </el-form-item>
        <el-form-item v-if="editinpStatus.files" label="目标文件" prop="files">
          <!--<el-input v-model="form.files"></el-input>-->
          <el-select v-model="form.target_hdfs_path" placeholder="请选择">
            <el-option
              v-for="item in multipleSelection"
              :label="`${currentDir}/${item.file_name}`"
              :value="`${currentDir}/${item.file_name}`">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="resetForm">取 消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="formButLoad">{{formBut}}</el-button>
      </div>
    </el-dialog>
    <!--快照-->
    <el-dialog v-model="dialog.snapshot" @close="resetForm">
      <div style="margin-bottom:5px;">
        <el-button @click="addSnapshotPrompt" size="small" type="primary">创建</el-button>
        <span>  当前目录： </span>
        <span>{{snapshotPath}}</span>
      </div>
      <el-table
        :data="snapshotTableData"
        style="width: 100%">
        <el-table-column prop="file_name" label="快照"></el-table-column>
        <el-table-column prop="last_updatetime" label="时间"></el-table-column>
        <el-table-column label="操作">
          <template scope="scope">
            <el-button type="text" size="small" @click="restoreSnapshot(scope)">恢复</el-button>
            <el-button type="text" size="small" @click="deleteSnapshot(scope)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm">取 消</el-button>
        <el-button type="primary" @click="dialog.snapshot = false">确 定</el-button>
      </span>
    </el-dialog>
  </section>
</template>

<script>
  import util from '../../common/util'
  import Search from '../../components/Search.vue'
  import UploadPath from '../../components/UploadPath.vue'
  import dao from '../../common/dao'
  import Conf from '../../common/cfg'
  import NProgress from 'nprogress'
  import {mapGetters} from 'vuex'

  export default {
    components: {Search, UploadPath},
    computed: {
      ...mapGetters([
        'getUser'
      ])
    },
    data() {
      return {
        userType: 0,
        canClick: true,
        timeout: null,
        visible: false,
        uploadUrl: `${Conf.APIURL}bdpmng/service/datamgt/hdfs/upload`,
        headers: {
          Authentication: Conf.HEADERS.Authentication,
          RJDATACENTERID: `${util.fetch('dataCenterId')}`
        },
        uploadBody: {hdfs_dir: ''},
        fileList: [],
        multipleSelection: [],
        page_count: 20,
        butStatus: {
          view: true,
          rename: true,
          delete: true,
          move: true,
          merge: true,
          download: true,
          create: true,
          upload: true,
          snapshot: true,
        },
        snapshotTableData: [],
        formLabelWidth: "120px",
        rules: {
          newDirectory: [
            {required: true, message: '请输入目录名称！', trigger: 'blur'},
            {validator: util.validateFileName, trigger: 'blur'}
          ],
          newName: [
            {required: true, message: '请输入新名字！', trigger: 'blur'},
            {validator: util.validateFileName, trigger: 'blur'}
          ],
          target_hdfs_path: [
            {required: true, message: '请输入新路径！', trigger: 'blur'},
          ],
          file_name: [
            {required: true, message: '请输入新建目录名称！', trigger: 'blur'},
            {validator: util.validateString, trigger: 'blur'}
          ]
        },
        dialog: {
          dialogTitle: "查看",
          log: false,
          form: false,
          snapshot: false,
        },
        editinpStatus: {
          directory: true,
          newDirectory: true,
          upfile: true,
          name: true,
          newName: true,
          path: true,
          newPath: true,
          selFile: true,
          files: true,
        },
        form: {
          type: "",
          file_name: "",
          hdfs_dir: "",
          upfile: "",
          newName: "",
          hdfs_path: "",
          target_hdfs_path: "",
          hdfs_paths: [],
          files: "",
        },
        tableData: [],
        formInline: {
          allOpts: [{
            key: 'directory',
            label: '目录',
            type: '',
            val: ''
          }],
          cOpts: [{
            key: 'directory',
            label: '目录',
            type: '',
            val: ''
          }]
        },
        snapshotPath: '',
        currentDir: '',
        nextDir: '',
        paths: [],
        root: '',
        rootDepth: 0,
        formBut: '确定',
        formButLoad: false,
        fileContent: '',
      }
    },
    methods: {
      search (val) { //调用查询服务
        this.getTableData();
      },
      ckr () {
        this.fileList = [];
      },
      getSnapshotTableData () {
        let obj = {};
        let sarr = this.formInline.cOpts || []
        sarr.map(item => {
          obj[item.key] = item.val;
        });
        obj.hdfs_dir = this.snapshotPath;
        dao.findByPath(obj).then(res => {
          if (res.FX.err) {
            return false
          }
          this.snapshotTableData = res.body.hdfs_files_list || [];
        }).catch(res => {
        })
      },
      openSnapshotForm () {

        if (this.multipleSelection.length > 0) {
          this.snapshotPath = `${this.currentDir}/${this.multipleSelection[0].file_name}/.snapshot`;
        } else {
          this.snapshotPath = `${this.currentDir}/.snapshot`;
        }

        this.getSnapshotTableData();
        this.dialog.snapshot = true;
      },
      addSnapshotPrompt () {
        this.$prompt('命名', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({value}) => {
          dao.createSnapshot({hdfs_path: this.snapshotPath, snapshotname: value}).then(res => {
            if (!res.body || res.body.retCode != '200') {
              util.apiMsg(res);
              return false;
            }
            this.getSnapshotTableData();
            this.$message({
              type: 'success',
              message: '成功 !'
            });
          }).catch(res => {
          })

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });
        });
      },
      hrm() {
        /*this.$alert('确定要删除该文件吗?', '提示', {
         confirmButtonText: '确定',
         }).then(res => {
         let deleteFile = '';
         for (let i = 0; i < this.multipleSelection.length; ++i) {
         deleteFile += `${this.currentDir}/${this.multipleSelection[i].file_name},`;
         }
         dao.deleteFile({hdfs_path: deleteFile}).then(res => {
         this.formButSta();
         if (!res.body || res.body.retCode != '200') {
         util.apiMsg(res);
         return false;
         }
         this.$message('删除成功');
         this.getTableData();
         }).catch(res => {
         this.formButSta();
         });
         });*/

        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          let deleteFile = '';
          for (let i = 0; i < this.multipleSelection.length; ++i) {
            deleteFile += `${this.currentDir}/${this.multipleSelection[i].file_name},`;
          }
          dao.deleteFile({hdfs_path: deleteFile}).then(res => {
            this.formButSta();
            if (!res.body || res.body.retCode != '200') {
              util.apiMsg(res);
              return false;
            }
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getTableData();

          }).catch(() => {

          });
        })
      },
      returnRoot(index) {
        this.fileList = [];
        this.nextDir = '/';
        if (index < this.rootDepth) {
          this.nextDir += this.paths.slice(0, this.rootDepth).join('/');
        } else {
          this.nextDir += this.paths.slice(0, index + 1).join('/');
        }
        this.getTableData();
      },
      downloadFile() {

        this.$confirm('确定要下载该文件吗？, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let downfile = `${this.currentDir}/${this.multipleSelection[0].file_name}`;
          dao.download({hdfs_path: downfile});
        }).catch(() => {
        });

      },
      handleAvatarSuccess(response, file, fileList){ //上传成功回调
        if(response.retCode!='200') {
          let tips = Conf.RESPONSE_WORK_BOOK[response.retCode].tips||'其他错误类型';
          this.$notify({
            title: '错误提示',
            message: `${response.retCode} : ${tips}`,
          });
          if (response.status == 401) this.$router.replace('/login');
          return false;
        }
        this.fileList = fileList;
        this.getTableData();
      },
      handleAvatarError(response, file, fileList){ //上传失败回调
        this.fileList = fileList
        let tips = Conf.RESPONSE_WORK_BOOK[response.retCode].tips||'其他错误类型';
        this.$notify({
          title: '错误提示',
          message: `${response.retCode} : ${tips}`,
        });
        if (response.status == 401) {
          this.$router.replace('/login')
        }
      },
      handlePreview(file){
        console.log(file);
      },
      handleRemove(file, fileList){
        console.log(file, fileList);
      },
      getEditInpShow() {
        return {
          add: ["directory", "newDirectory"],
          upload: ["upfile"],
          rename: ["name", "newName"],
          mv: ["path", "newPath"],
          merge: ["selFile", "files"],
        }
      },
      updateTable (row) {

        this.fileList = [];
        this.nextDir = `${this.currentDir}/${row.file_name}`;
        this.formInline.cOpts.map(item => {
          item.val = ''
        });
        this.getTableData();
      },
      updateEditInpStatus() {
        let type = this.form.type;
        let arr = this.getEditInpShow()[type];
        for (let key in this.editinpStatus) {
          if (arr.indexOf(key) > -1) this.editinpStatus[key] = true;
          else this.editinpStatus[key] = false;
        }

      },
      handleSelectionChange (val) {
        this.multipleSelection = val;
        this.cgToolBTSta(val)
      },
      getTableData () {
        let obj = {};
        let sarr = this.formInline.cOpts || [];
        sarr.map(item => {
          obj[item.key] = item.val;
        });

        obj.hdfs_dir = this.nextDir;

        dao.findByPath(obj).then(res => {
          if (!res.body || res.body.retCode != '200') {
            this.nextDir = this.currentDir;
            util.apiMsg(res);
            return false;
          }

          this.currentDir = this.nextDir;

          let path = this.nextDir.slice(1);
          this.paths = path.split('/');

          this.resetButtonStatus();

          this.tableData = res.body.hdfs_files_list || [];
          this.uploadBody.hdfs_dir = this.currentDir;
        })
      },
      resetButtonStatus () {
        this.userType = util.fetch('user_type') || 0;
        let isAdministrator = ( this.userType == Conf.adminUserType)
        if (isAdministrator) {
          this.butStatus = {
            view: true,
            rename: true,
            delete: true,
            move: true,
            merge: true,
            download: true,
            create: false,
            upload: false,
            snapshot: false,
          }
          //this.canClick = true;
        } else if (this.root == this.currentDir) {
          this.butStatus = {
            view: true,
            rename: true,
            delete: true,
            move: true,
            merge: true,
            download: true,
            create: true,
            upload: true,
            snapshot: true,
          }
        } else {
          this.butStatus = {
            view: true,
            rename: true,
            delete: true,
            move: true,
            merge: true,
            download: true,
            create: false,
            upload: false,
            snapshot: true,
          }
          //this.canClick = true;
        }
      },
      cgToolBTSta(val = []){
        this.userType = util.fetch('user_type') || 0;
         let isAdmin = this.userType == 1
        let isRootPath = this.paths.length == 1
        if(!isAdmin&&isRootPath){
          this.butStatus = {
            view: true,
            rename: true,
            delete: true,
            move: true,
            merge: true,
            download: true,
            create: true,
            upload: true,
            snapshot: true,
          }
        } else
        if (val.length == 0) {
          this.resetButtonStatus();
        } else if (val.length == 1) {
          let isDir = (val[0].isdirectory == 1)
          this.butStatus = {
            view: isDir,
            rename: false,
            delete: false,
            move: false,
            merge: true,
            download: isDir,
            create: false,
            upload: false,
            snapshot: this.butStatus.snapshot,
          }
        } else {
          let isMerge = false;
          for (let item of val) {
            if (item.isdirectory == 1) {
              isMerge = true;
              break;
            }
          }
          this.butStatus = {
            view: true,
            rename: true,
            delete: false,
            move: true,
            merge: isMerge,
            download: true,
            create: false,
            upload: false,
            snapshot: this.butStatus.snapshot,
          }
        }
      },
      showForm (type) {

        this.form.newName = '';
        this.form.hdfs_dir = this.currentDir;
        switch (type) {
          case 'rename':
          case 'mv':
            if (this.multipleSelection.length == 1) {
              this.form.hdfs_dir += `/${this.multipleSelection[0].file_name}`;
              this.form.target_hdfs_path = '';
              this.form.newName = ''
            }
            break;
          default:
            break;
        }
        this.form.type = type;
        this.updateEditInpStatus()
        this.dialog.form = true;
      },
      createDir(){
        dao.mkdir({hdfs_dir: this.form.hdfs_dir, file_name: this.form.file_name}).then(res => {
          this.formButSta();
          if (!res.body || res.body.retCode != '200') {
            util.apiMsg(res);
            return false;
          }
          this.$message({
            message: '创建成功',
            type: 'success'
          });
          this.getTableData();
          this.form.file_name = "";
        }).catch(res => {
          this.formButSta();
        });
      },
      moveDir () {
        dao.moveFile({
          hdfs_path: this.form.hdfs_dir,
          target_hdfs_path: this.form.target_hdfs_path
        }).then(res => {
          this.formButSta();
          if (!res.body || res.body.retCode != '200') {
            util.apiMsg(res);
            return false;
          }
          this.$message({
            message: '移动成功',
            type: 'success'
          });
          this.getTableData();
        }).catch(res => {
          this.formButSta();
        });
      },
      reName () {
        dao.renameFile({hdfs_path: this.form.hdfs_dir, newname: this.form.newName}).then(res => {
          this.formButSta();
          if (!res.body || res.body.retCode != '200') {
            util.apiMsg(res);
            return false;
          }
          this.$message({
            message: '重命名成功',
            type: 'success'
          });
          this.getTableData();
        }).catch(res => {
          this.formButSta();
        });
      },
      mergeFile () {
        this.form.hdfs_paths = [];
        let file = '';
        for (let i in this.multipleSelection) {
          file = `${this.currentDir}/${this.multipleSelection[i].file_name}`;
          if (file != this.form.target_hdfs_path) {
            this.form.hdfs_paths.push(file);
          }
        }
        dao.concatFiles({src_paths: this.form.hdfs_paths, dest_path: this.form.target_hdfs_path}).then(res => {
          this.formButSta();
          if (!res.body || res.body.retCode != '200') {
            util.apiMsg(res);
            return false;
          }
          this.$message({
            message: '合并成功',
            type: 'success'
          });
          this.getTableData();
        }).catch(res => {
          this.formButSta();
        });
      },
      readFile () {
        this.formTitle = '查看文件'
        this.dialog.log = true;
        let hdfs_path = `${this.currentDir}/${this.multipleSelection[0].file_name}`;
        dao.readFile({hdfs_path: hdfs_path}).then(res => {
          if (!res.body || res.body.retCode != '200') {
            util.apiMsg(res);
            return false;
          }
          this.fileContent = res.body.file_content;

        }).catch(res => {
        })
      },
      uploadFile () {
      },
      formButSta(type){
        if (type) {
          this.formBut = "提交中";
          this.formButLoad = true;
        } else {
          this.formBut = "确定";
          this.formButLoad = false;
          this.dialog.form = false;
        }
      },
      editSubmit () {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return false
          }
          this.formButSta(true);
          switch (this.form.type) {
            case 'add':
              this.createDir();
              break;
            case 'rename':
              this.reName();
              break;
            case 'mv':
              this.moveDir();
              break;
            case 'upload':
              this.getTableData();
              this.formButSta(false);
              break;
            case 'merge':
              this.mergeFile();
              break;
            default:
              break;
          }
        })
      },
      restoreSnapshot (scope) {
        this.$confirm('此操作将恢复该快照, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          dao.restoreSnapshot({hdfs_path: this.snapshotPath, snapshotname: scope.row.file_name}).then(res => {

            if (!res.body || ret.body.retCode != '200') {
              this.$message('恢复有误');
              return false;
            }
            this.$message({
              message: '恢复成功',
              type: 'success'
            });
          }).catch(res => {
          })
        }).catch(() => {
          this.$message({
            type: 'info',//success
            message: '已取消'
          });
        });
      },
      deleteSnapshot (scope) {
        this.$confirm('此操作将删除该快照, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return dao.deleteSnapshot({hdfs_path: this.snapshotPath, snapshotname: scope.row.file_name})
        }).then(res => {
          if (!res.body || ret.body.retCode != '200') {
            this.$message('删除有误');
            return false;
          }
          this.getSnapshotTableData();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
        }, res => {

        }).catch(() => {
          this.$message({
            type: 'info',//success
            message: '已取消删除'
          });
        });
      },
      resetForm () { //重置表单
        this.$refs.form.resetFields();
        this.dialog.snapshot = false;
        this.dialog.form = false;
      }
    },
    mounted () {

      this.root = Conf.tenentRoot.replace(/(\/*$)/g, "");
      this.currentDir = this.root;
      this.nextDir = this.root;
      this.paths = this.root.split('/');
      this.paths = this.paths.slice(1);
      this.rootDepth = this.paths.length;
      this.getTableData();

    }
  }
</script>

<style scoped>
  span.el-breadcrumb {
    padding-left: 10px;
    margin-bottom: 5px;
    margin: 0 2px;
  }

  .dirtips.el-breadcrumb__separator {
    margin: 0 2px;
    color: #20a0ff;
  }

  .dirtips.el-breadcrumb__item__inner {
    color: #20a0ff;
  }

  .udfs-list {
    margin-top: 0px;
    margin-bottom: 8px;
  }
</style>